import { getUserAgent } from './utils'

export class ViewManager {
  constructor(mainWindow, view, url, session = null) {
    this.mainWindow = mainWindow
    this.view = view
    this.url = url
    this.session = session || view.webContents.session
  }

  destory () {
    this.mainWindow.removeBrowserView(this.view)
  }

  show() {
    this.mainWindow.setTopBrowserView(this.view)
  }

  reload () {
    this.view.webContents.reload()
  }

  forward () {
    this.view.webContents.goForward()
  }

  retreat () {
    this.view.webContents.goBack()
  }

  resize (bounds) {
    this.view.setBounds(bounds)
  }

  beforeRequest (channel, callback) {
    this.session.webRequest.onBeforeSendHeaders((details, requestCallback) => {
      if (details.url.indexOf(channel) > -1) {
        callback({ headers: details.requestHeaders })
      }

      requestCallback({ requestHeaders: details.requestHeaders })
    });
  }

  executeJavaScript (code, callback) {
    this.view.webContents.executeJavaScript(code).then((result) => {
      callback(result)
    })
  }

  navigateDidEvent (callback) {
    const navigateHandler = (_, url) => {
      callback(url)
    }

    this.view.webContents.on('did-navigate', navigateHandler)
    this.view.webContents.on('did-navigate-in-page', navigateHandler)
  }

  finishLoadEvent (callback) {
    const loadHandler = () => {
      callback(this.view.webContents.getURL())
    }

    this.view.webContents.on('did-finish-load', loadHandler)
  }

  navigateTo (url, userAgent) {
    this.view.webContents.loadURL(url, {
      userAgent: userAgent || getUserAgent(this.mainWindow)
    })
  }

  fetchCookies (callback) {
    const url = new URL(this.url)

    this.session.cookies.get({url: url.origin}).then(cookies => {
      callback(cookies)
    }).catch(error => {
      console.error(`获取Cookies失败: ${error}`);
    })
  }

  clearCache () {
    this.session.clearCache()

    this.session.clearStorageData({
      storages: ['localstorage', 'sessionstorage', 'cookies']
    }, () => {

    })

    this.session.cookies.get({}).then(cookies => {
      cookies.forEach(cookie => {
        let url = '';
        if (cookie.secure) {
          url += 'https://';
        } else {
          url += 'http://';
        }
        url += cookie.domain + cookie.path;

        this.session.cookies.remove(url, cookie.name).then(() => {
          console.log('Cookie已删除');
        }).catch(error => {
          console.error(`Cookie 删除失败: ${error}`);
        })
      })
    }).catch(error => {
      console.error(`获取Cookies失败: ${error}`);
    })
  }
}
